<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">

    <!-- <el-radio-group v-model="isCollapse" @change="change" style="margin-bottom: 20px;">
      <el-radio-button :label="true"><i class="el-icon-s-data"></i>图表</el-radio-button>
      <el-radio-button :label="false"><i class="el-icon-menu"></i>表格</el-radio-button>
    </el-radio-group> -->

    <div v-if="!isCollapse">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <!-- <el-input
        @keyup.enter.native="getData"
        clearable
        v-model="param.orderType"
        style="width: 150px;margin-right:15px;"
        class="filter-item"
        placeholder="请输入单别"
      ></el-input>
      <el-input
        @keyup.enter.native="getData"
        clearable
        v-model="param.workOrderNo"
        style="width: 150px;margin-right:15px;"
        class="filter-item"
        placeholder="请输入单号"
      ></el-input> -->
      <!-- style="width: 150px;margin-right:15px;" -->
      <el-input
        @keyup.enter.native="getData"
        clearable
        v-model="param.machineId"
        style="margin-right: 15px;"
        :style="{ width: inputWid(param.machineId) }"
        placeholder="请输入设备号"
      ></el-input>
      <el-input
        @keyup.enter.native="getData"
        clearable
        v-model="param.technologyNo"
        style="margin-right: 15px;"
        :style="{ width: inputWid(param.technologyNo) }"
        placeholder="请输入品号"
      ></el-input>
      <el-input
        @keyup.enter.native="getData"
        clearable
        v-model="param.planBatchNumber"
        style="margin-right: 15px;"
        :style="{ width: inputWid(param.planBatchNumber) }"
        placeholder="请输入计划批号"
      ></el-input>
      <el-input
        @keyup.enter.native="getData"
        clearable
        v-model="param.deviceBarcode"
        style="margin-right: 15px;"
        :style="{ width: inputWid(param.deviceBarcode) }"
        placeholder="请输入工序条码"
      ></el-input>
      <el-select
        clearable
        v-model="param.isEnd" 
        placeholder="请选择状态" 
        style="width: 150px;margin-right:15px;">
            <el-option 
            :value="item" 
            :label="item" v-for="(item,index) in this.statusList" 
            :key="index"/>
      </el-select>
      <el-date-picker
          v-model="dateOptions"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          style="margin-right: 15px;">
        </el-date-picker>

      <el-button style="margin-right:15px;" type="primary" v-waves icon="el-icon-search" @click="getData">查询</el-button>

    </div>
    
    <!-- table 表格 -->
    <el-table  :data="tableInfo" :height="height" v-loading="loadingList" element-loading-text="给我一首歌的时间" border fit :row-style="rowstyles" style="width: 100%;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column  label="设备号"  prop="machineId" align="center" width="140"/>
      <el-table-column  label="工序条码"  prop="deviceBarcode" align="center" width="100"/>
      <!-- <el-table-column  label="工单单别"  prop="orderType" align="center"/> -->
      <el-table-column  label="工单单号"  prop="workOrderNo" align="center"/>
      <el-table-column  label="排产序号"  prop="planNo" align="center" width="100" style="white-space:pre-wrap"/>
      <el-table-column  label="计划批号"  prop="orderPlanNo" align="center" width="100" style="white-space:pre-wrap"/>
      <el-table-column  label="品号"  prop="technologyNo" align="center"/>
      <el-table-column  label="品名"  prop="technologyName" align="center"/>
      <el-table-column  label="规格"  prop="specification" align="center"/>
      <el-table-column  label="工艺名称"  prop="pmProcessName" align="center"/>
      <el-table-column  label="开始时间"  prop="beginTime" align="center"/>
      <el-table-column  label="结束时间"  prop="finishTime" align="center"/>
      <!-- <el-table-column  label="工序" prop='processName' align="center"/>
      <el-table-column  label="工序编号" prop='processSerial' align="center"/>
      <el-table-column  label="班次"  prop="planNo" align="center"/> -->
      <el-table-column  label="零件数量" prop='predictOutput1' align="center"/>
      <el-table-column  label="扫码数量" prop='scanQuantity' align="center"/>
      <el-table-column  label="生产达成率(%)" prop='paRate' align="center"/>
      <el-table-column label="状态" prop="isEnd" align="center">
        <template slot-scope="scope">
          <div class="fx">
            {{
              scope.row.isEnd  == '1'? "完工"
              : scope.row.isEnd  == '2'? "停产"
              : scope.row.isEnd  == '0'
                ? "未完工"
                : "-"
            }}
           </div>
        </template>
      </el-table-column>
    </el-table>
   
   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

    <el-divider></el-divider>
    </div>
    <!-- <span class="charts-title">选择日、周、月、年查看图表</span> -->
    <div v-else>
    <el-date-picker
      v-model="value0"
      type="date"
      style="margin-right:15px;margin-bottom:10px"
      placeholder="选择日期"
      @change="dates">
    </el-date-picker>

    <el-date-picker
      v-model="value1"
      type="week"
      style="margin-right:15px;margin-bottom:10px"
      format="yyyy 第 WW 周"
      value-format="yyyy-M-d"
      placeholder="选择周"
      @change="weeks">
    </el-date-picker>

    <el-date-picker
      v-model="value2"
      type="month"
      value-format="yyyy-MM"
      style="margin-right:15px;margin-bottom:10px"
      placeholder="选择月"
      @change="months">
    </el-date-picker>

    <el-date-picker
      v-model="value3"
      type="year"
      value-format="yyyy-MM"
      style="margin-right:15px;margin-bottom:10px"
      placeholder="选择年"
      @change="years">
    </el-date-picker>
    <!-- 折线图 -->
    <div class="echart" id="main" :style="myChartStyle"></div>
    </div>

  </div>
</template>

<script>
import { findSchedule } from '@/api/CNCmachine.js'
export default {
    name: 'proEfficiency',
    data() {
        return {
            total: 0,     //数据的总数
            listQuery: {
              page: 1,                          //页码
              limit: 10                        //每页显示的数据条数
            },
            param: {
              machineId: '',                    //机台号
              planBatchNumber: '',               //计划批号
              isEnd: '未完工'                         //0未完工,1完工,2停产
            },
            tableInfo: [],
            loadingList: false,
            myChartStyle: { float: "left", width: "100%", height: "520px",background:"#fff" }, //图表样式
            opinionData: ["10", "30", "20", "50", "5", "15", "40","20", "40", "20", "20", "5", "15", "40"], //数据
            opinionData2: ["10", "28", "15", "30", "5", "14", "20","10", "28", "15", "10", "5", "14", "20"], //数据
            xdata: ["2022-05-01","2022-05-02","2022-05-03","2022-05-04","2022-05-05","2022-05-06","2022-05-07","2022-05-08","2022-05-09","2022-05-10","2022-05-11","2022-05-12","2022-05-13","2022-05-14","2022-05-15","2022-05-16","2022-05-17","2022-05-18","2022-05-19","2022-05-20","2022-05-21","2022-05-22","2022-05-23"],
            activeName: 'days',
            value0: '',
            value1: '',
            value2: '',
            value3: '',
            endData: 35,
            isCollapse: false,
            loading: false,
            statusList: ['未完工','完工','停产'],
            height: 650,
            dateOptions: this.getNowTime(),
            pickerOptions: {
              shortcuts: [{
                text: '最近一周',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近一个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近三个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                  picker.$emit('pick', [start, end]);
                }
              }]
            },
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
      //初始默认执行(重点)，返回日期格式YYYY-MM-DD HH:MM:SS
      getNowTime() {
          let dateTime = +new Date()+8*3600*1000
          const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
              .toISOString()
              .replace('T', ' ')
              .split('.')[0]
              // .substring(0,10) //默认开始时间7天前
          const end = new Date(dateTime)
              .toISOString()
              .replace('T', ' ')
              .split('.')[0]
              // .substring(0,10)//默认结束时间当前时间
          console.log([start, end])
          return [start, end]
        },
      rowstyles({row,rowIndex}){
        console.log('rowstyles',row)
        if(row.isEnd == 1){
          return {"background": "#dbf1e1"}
        } else if(row.isEnd == 2) {
          return {"background": "#f4f4f5"}
        } else if(row.isEnd == 0) {
          return {"background": "#fef0f0"}
        }
      },
      transformDat(res) {
        // console.log('%c导出质量系数excel数据:','color:green;font-size:16px;')
        // console.log(res)
        const mapInfo = {
          index: '序号',
          machineId: '设备号',
          // orderType: '单别',
          workOrderNo: '工单单号',
          planNo: '排产序号',
          orderPlanNo: '计划批号',
          technologyNo: '品号',
          technologyName: '品名',
          specification: '规格',
          pmProcessName: '工序名称',
          beginTime: '开始时间',
          finishTime: '结束时间',
          deviceBarcode: '工序条码',
          predictOutput1: '零件数量',
          scanQuantity: '扫码数量',
          paRate: '生产达成率(%)',
          isEnd: '是否完成'
        }
        // 对data进行格式化
        // 取出所有的属性名
        const props = Object.keys(res[0]) // ['id','']
        // 将属性名从英文转为中文
        const header = props.map(zhkey => mapInfo[zhkey])
        // const data=[['xxxx','总裁办'，'13800000']]
        const data = res.map(obj => Object.values(obj))
        return { header, data }
      },
      // 导出excel
      async hExportExcel() {
        this.loading = true
        let query = Object.assign({},this.listQuery)
        if(this.param.machineId){query.machineId = this.param.machineId}
        // if(this.param.orderType){query.orderType = this.param.orderType}
        if(this.param.workOrderNo){query.workOrderNo = this.param.workOrderNo}
        if(this.param.technologyNo) { query.technologyNo = this.param.technologyNo }
        if(this.param.planBatchNumber){query.planBatchNumber = this.param.planBatchNumber}
        if(this.param.deviceBarcode){query.deviceBarcode = this.param.deviceBarcode}
        if(this.param.isEnd != ''){query.isEnd = this.param.isEnd == '未完工'?0:this.param.isEnd == '完工'?1:2}
        query.page = 1
        query.limit = 1000000
        console.log('%c导出excel传的参数query:','color:green;font-size:16px;')
        console.log(query)

        let datas = await findSchedule(query)
        let errMsg = datas.msg
        if(datas.code != '1'){
          this.loading = false
          this.$message({
            type: 'warning',
            message: errMsg
          })
          return
        }
        let datas1 = JSON.parse(JSON.stringify(datas.data.list))
        datas1.forEach(item => {
          item.predictOutput1 = parseInt(item.count)
        });
        const { header, data } = this.transformDat(this.setSort(datas1))
          import('@/vendor/Export2Excel').then(excel => {
          // excel表示导入的模块对象
          console.log(excel)
          excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '工序生产达成率excel', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
          })
        })
        this.loading = false
      },
      // 排序函数
      setSort(arr){
        let newArr = JSON.parse(JSON.stringify(arr))
        let arr1 = []
        newArr.forEach((item,index)=>{
          let obj = {
            index: index+1,
            machineId: item.machineId,
            // orderType: item.orderType,
            workOrderNo: item.workOrderNo,
            planNo: item.planNo,
            orderPlanNo: item.orderPlanNo,
            technologyNo: item.technologyNo,
            technologyName: item.technologyName,
            specification: item.specification,
            pmProcessName: item.pmProcessName,
            beginTime: item.beginTime,
            finishTime: item.finishTime,
            deviceBarcode: item.deviceBarcode,
            predictOutput1: item.predictOutput1,
            scanQuantity: item.scanQuantity,
            paRate: ((parseInt(item.scanQuantity)/parseInt(item.count))*100).toFixed(2),
            isEnd: item.isEnd
          }
          arr1.push(obj)
        })
        return arr1
      },
      // 搜索按钮绑定的函数，向服务器发送表单数据
      // 所有传输的表单字段都不是必须的，按需查询
      async handleFilter() {
        let query = Object.assign({},this.listQuery)
        if(this.param.machineId){query.machineId = this.param.machineId}
        // if(this.param.orderType){query.orderType = this.param.orderType}
        if(this.param.workOrderNo){query.workOrderNo = this.param.workOrderNo}
        if(this.param.technologyNo) { query.technologyNo = this.param.technologyNo }
        if(this.param.planBatchNumber){query.planBatchNumber = this.param.planBatchNumber}
        if(this.param.deviceBarcode){query.deviceBarcode = this.param.deviceBarcode}
        if(this.param.isEnd != ''){query.isEnd = this.param.isEnd == '未完工'?0:this.param.isEnd == '完工'?1:2}
        if(this.dateOptions) {
              if(this.dateOptions.length) {
                  query.strTime = this.dateOptions[0]
                  query.endTime = this.dateOptions[1]
              }
            }
        this.loadingList = true
        console.log('%c/back/machineBack/findSchedule接口传参:','color:red;font-size:16px;')
        console.log('query',query)
        let data = await findSchedule(query)
        let errMsg = data.msg
        this.loadingList = false
        if(data.code == '1'){
          if(!data.data.list.length){
            this.tableInfo = []
            this.total = 0
            this.height = ''
            return
          }
          let datas = JSON.parse(JSON.stringify(data.data.list))
          datas.forEach(item => {
            item.predictOutput1 = parseInt(item.count)
            item.paRate = ((parseInt(item.scanQuantity)/parseInt(item.count))*100).toFixed(2)
          });
          this.tableInfo = datas
          this.total = data.data.totle
          if(this.tableInfo.length<10){this.height = ''} else {this.height = 650}
        } else{
          this.$message({
            type: 'warning',
            message: errMsg
          })
        }
      },
      // table表单下方的页码组件改变每页显示的数据条数
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.handleFilter()
      },
      // table表单下方的页码组件改变页面
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.handleFilter()
      },
      getData() {
        this.listQuery.page = 1
        this.listQuery.limit = 10
        this.handleFilter()
      },
      handleClick(tab, event) {
          console.log(tab, event);
      },
      // 折线图
      drawLine() {
        this.charts = this.$echarts.init(document.getElementById('main'))
        this.charts.clear()
        this.charts.setOption({
            title:{
            left:'3%',
            top:'5%',
            text:"生产效率",//标题文本，支持使用 \n 换行。
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
            align:'right',//文字在前图标在后
            left:'3%',
            top:'15%',
            data: ['实际完成工单数','应完成工单数']
        },
        grid: {
            top:'30%',
            left: '3%',
            right: '3%',
            bottom: '20%',
            containLabel: true
        },
    
        toolbox: {
          feature: {
            saveAsImage: {} //保存为图片
          }
        },
        xAxis: {
            name: '时间',
            type: 'category',
            boundaryGap:false,
            axisTick:{
              alignWithLabel:true //保证刻度线和标签对齐
            },
            data: this.xdata //x坐标的名称   
        },
        yAxis: {
            name: '工单数',
            type: 'value',
            boundaryGap: true,
            splitNumber:4, //纵坐标数
            interval:10 //强制设置坐标轴分割间隔
        },
        // x轴拖动
        dataZoom: [
            {
              type: "slider",
              realtime: true, //拖动滚动条时是否动态的更新图表数据
              height: 30, //滚动条高度
              start: 0, //滚动条开始位置（共100等份）
              end: this.endData //结束位置（共100等份）
            }
        ],
        label: {
          show: true,
          position: 'bottom',
          textStyle: {
            color: 'rgb(255,255,255)'
          }
        },
        // animation:false,   停止初始化动画
        series: [
          {
            name: '应完成工单数',
            type: 'line', //折线图line;柱形图bar;饼图pie
            // stack: '总量',
            smooth:true,
            areaStyle: {
                //显示区域颜色---渐变效果
                color:{
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [],   //渐变区间暂时去掉，因为会报错
                  global: false // 缺省为 false
                }
              },
              itemStyle: {
                color: 'rgb(255,96,64)', //改变折线点的颜色
                lineStyle: {
                  color: 'rgb(255,96,64)' //改变折线颜色
                }
              },
            data: this.opinionData
          },
          {
            name: '实际完成工单数',
            smooth:true,
            type: 'line', //折线图line;柱形图bar;饼图pie
            // stack: '总量',
            areaStyle: {
                //显示区域颜色---渐变效果
              color:{
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [],   //渐变区间暂时去掉，因为会报错
                global: false // 缺省为 false
              }
              // {
              //     offset: 0, color: 'rgb(245,252,255)' // 0% 处的颜色
              //   }, {
              //     offset: 1, color: 'rgb(68,114,197,0.1)' // 100% 处的颜色
              //   }
            },
            itemStyle: {
              color: 'rgb(68,114,197)', //改变折线点的颜色
              lineStyle: {
                color: 'rgb(255,96,64)' //改变折线颜色
              }
            },
            data: this.opinionData2
          }]
        })
        let _this= this
        window.addEventListener("resize", () => {
          if(_this.charts){
            _this.charts.resize();
          }
        });
      },
      dates(e) {
          console.log('dates',this.value0)
          this.clearData('dates')
          let hours = []
          for(let i = 1; i <= 24; i++){
            let str = i + ':00'
            hours.push(str)
          }
          this.xdata = hours
          this.endData = 50
          this.opinionData = ["10", "30", "20", "50", "5", "15", "40","20", "40", "20", "20", "5", "15", "40","20","30","10","25","15","13","20","30","50","10"]
          this.opinionData2 = ["10", "20", "10", "40", "5", "14", "30","20", "35", "10", "20", "5", "10", "26","10","15","5","20","12","10","10","30","40","10"]
          this.drawLine()
      },
      weeks(e) {
          this.clearData('weeks')
          this.xdata = this.dealWeeks()
          this.endData = 100
          this.opinionData = ["10", "30", "20", "50", "5", "15", "40"]
          this.opinionData2 = ["10", "20", "15", "30", "5", "12", "30"]
          this.drawLine()
      },
      months(e) {
          console.log('weemonthsks',this.value2)
          this.clearData('months')
          let ym = this.value2.split('-')
          let days = this.getDaysInMonth(ym[0],ym[1])
          let month = []
          for(let i = 1; i <= days; i++){
            let str = ym[0] + '-' + ym[1] + '-' + this.dateComplete(i)
            month.push(str)
          }
          this.xdata = month
          this.endData = 30
          this.opinionData = ["10", "30", "20", "50", "5", "15", "40","20", "40", "20", "20", "5", "15", "40","20","30","10","25","15","13","20","30","50","10","13","20","30","50","10"]
          this.opinionData2 = ["10", "20", "10", "40", "5", "14", "30","20", "35", "10", "20", "5", "10", "26","10","15","5","20","12","10","10","30","40","10","10","10","30","40","10"]
          this.drawLine()
          console.log('当前月的天数',days,month)
      },
      dateComplete(day) {
        return day<10?'0'+day:day
      },
      monthComplete(month) {
        return month>12?1:month
      },
      monthPt(month){
        return month<1?12:month
      },
      years() {
          console.log('years',this.value3)
          let ym = this.value3.split('-')
          this.clearData('years')
          let years = []
          for(let i = 1; i <= 12; i++){
            let str = ym[0] + '-' + this.dateComplete(i)
            years.push(str)
          }
          this.xdata = years
          this.endData = 100
          this.opinionData = ["10", "30", "20", "50", "5", "15", "40","20", "40", "20", "20", "5"]
          this.opinionData2 = ["10", "20", "10", "40", "5", "14", "30","20", "35", "10", "20", "5"]
          this.drawLine()
      },
      clearData(type){
        if (type == 'dates') {
          this.value1 = ''
          this.value2 = ''
          this.value3 = ''
        } else if (type == 'weeks') {
          this.value0 = ''
          this.value2 = ''
          this.value3 = ''
        } else if(type == 'months') {
          this.value0 = ''
          this.value1 = ''
          this.value3 = ''
        } else if (type == 'years') {
          this.value0 = ''
          this.value1 = ''
          this.value2 = ''
        }
      },
      getDaysInMonth(year,month){
          let temp = new Date(year,month,0);
          return temp.getDate();
      },
      dealWeeks(){
        let ym = this.value1.split('-')
        let days = this.getDaysInMonth(ym[0],ym[1])
        console.log('weeks',ym,days,this.value1)
        let week = []
        if (days - parseInt(ym[2]) >=5 && days - parseInt(ym[2]) < 30) {
          for(let i = 0; i <= 6; i++){
            let str = ym[0] + '-' + ym[1] + '-' + this.dateComplete(parseInt(ym[2])-1 + i)
            week.push(str)
          }
          console.log('常规周数',week)
        } else {
          if (parseInt(ym[2])>7) {
            for(let i = 0; i <= days-parseInt(ym[2])+1; i++){
              let str = ym[0] + '-' + ym[1] + '-' + this.dateComplete(parseInt(ym[2])-1 + i)
              week.push(str)
            }
            let newMonth = this.monthComplete(parseInt(ym[1])+1)
            for(let i = 0; i <= 6-(days-parseInt(ym[2]))-2; i++){
              let str = parseInt(ym[1])+1>12?parseInt(ym[0])+1 + '-' + newMonth + '-' + this.dateComplete(i+1):ym[0] + '-' + newMonth + '-' + this.dateComplete(i+1)
              week.push(str)
            }
          } else{
            if (parseInt(ym[2])-1<1){
              let newdays = this.getDaysInMonth(ym[0],ym[1]-1)
              let newMonth = this.monthPt(parseInt(ym[1])-1)
              let str = parseInt(ym[1])-1<1?parseInt(ym[0])-1 + '-' + newMonth + '-' + newdays:ym[0] + '-' + newMonth + '-' + newdays
              week.push(str)
              for(let i = 1; i <= 6; i++){
                let str = ym[0] + '-' + ym[1] + '-' + this.dateComplete(i)
                week.push(str)
              }
            }
          }
          console.log('不常规周数',week,parseInt(ym[2]),days)
        }
        return week
      },
      change() {
        if(this.isCollapse){
          this.drawLine()
        } else {
          if(this.charts) {
            this.resetChart()
          }
        }
      },
      resetChart() {
        this.charts.clear()
        this.charts.dispose()
        this.charts = null
        window.removeEventListener('resize', () => { this.charts.resize() })
      }
  },
  // 进入页面获取table信息
  mounted() {
        this.handleFilter()
  },
  beforeDestroy() {
    if (this.charts) {
       this.resetChart()
    }
  },
}
</script>

<style>
.blank{
    width: 100%;
    height: 50px;
}
</style>